<template>
  <Modal
    :title="
      $t('daprplus.auth.resource.editOperations', { name: resource.name })
    "
    :open="open"
    :width="900"
    @update:open="(val) => emit('update:open', val)"
    @ok="handleSubmit"
    :confirmLoading="submitting"
  >
    <div class="operations-form">
      <!-- 表头 -->
      <div class="operation-header">
        <div class="header-code">操作代码</div>
        <div class="header-display">显示名称</div>
        <div class="header-color">颜色</div>
        <div class="header-preview">预览</div>
        <div class="header-access-type">访问类型</div>
      </div>

      <!-- 操作列表 -->
      <div
        v-for="(op, index) in operations"
        :key="index"
        class="operation-item"
      >
        <div class="operation-row">
          <div class="operation-code">{{ op.code }}</div>
          <Input
            v-model:value="op.display"
            :placeholder="$t('daprplus.auth.resource.operationDisplay')"
            class="operation-input"
          />
          <Select
            v-model:value="op.color"
            :placeholder="$t('daprplus.auth.resource.operationColor')"
            class="operation-color-select"
          >
            <Option value="blue"
              ><span class="color-dot blue"></span>蓝色</Option
            >
            <Option value="red"><span class="color-dot red"></span>红色</Option>
            <Option value="green"
              ><span class="color-dot green"></span>绿色</Option
            >
            <Option value="orange"
              ><span class="color-dot orange"></span>橙色</Option
            >
            <Option value="purple"
              ><span class="color-dot purple"></span>紫色</Option
            >
            <Option value="gold"
              ><span class="color-dot gold"></span>金色</Option
            >
            <Option value="magenta"
              ><span class="color-dot magenta"></span>品红</Option
            >
            <Option value="lime"
              ><span class="color-dot lime"></span>青柠</Option
            >
            <Option value="volcano"
              ><span class="color-dot volcano"></span>火山红</Option
            >
            <Option value="geekblue"
              ><span class="color-dot geekblue"></span>深蓝</Option
            >
            <Option value="gray"
              ><span class="color-dot gray"></span>灰色</Option
            >
            <Option value="cyan"
              ><span class="color-dot cyan"></span>青色</Option
            >
          </Select>
          <Tag :color="op.color || 'blue'" class="preview-tag">{{
            op.display
          }}</Tag>
          <Select
            v-model:value="op.accessType"
            :placeholder="'访问类型'"
            class="operation-access-type-select"
          >
            <Option :value="ResourceAccessType.None">未限制</Option>
            <Option :value="ResourceAccessType.Anonymous">匿名访问</Option>
            <Option :value="ResourceAccessType.LoggedIn">登录访问</Option>
            <Option :value="ResourceAccessType.RoleLimit">角色限制</Option>
          </Select>
        </div>
      </div>
    </div>
  </Modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { Modal, Input, Select, Tag, message } from 'ant-design-vue';
import type {
  ResourceOutDto,
  ResourceOperation,
  ResourceInDto,
} from '#/api/daprplus/auth/resource';
import {
  ResourceAccessType,
  updateResourcesApi,
} from '#/api/daprplus/auth/resource';

const { Option } = Select;

const props = defineProps<{
  open: boolean;
  resource: ResourceOutDto;
  service: string;
}>();

const emit = defineEmits<{
  'update:open': [value: boolean];
  success: [];
}>();

// 操作列表
const operations = ref<ResourceOperation[]>([]);

// 加载状态
const submitting = ref(false);

// 监听resource变化，初始化operations
watch(
  () => props.resource,
  (newResource) => {
    if (newResource && newResource.allowedOperations) {
      operations.value = [...newResource.allowedOperations].map((op) => {
        op = getDefaultColor(op);
        return op;
      });
    } else {
      operations.value = [];
    }
  },
  { immediate: true },
);

// 获取默认颜色
function getDefaultColor(op: ResourceOperation): ResourceOperation {
  const lowerCode = op.code.toLowerCase();

  switch (lowerCode) {
    case 'read':
      op.color = 'orange';
      op.display = '读取';
      break;
    case 'getpage':
      op.color = 'orange';
      op.display = '分页';
      break;
    case 'create':
      op.color = 'green';
      op.display = '创建';
      break;
    case 'update':
      op.color = 'blue';
      op.display = '更新';
      break;
    case 'delete':
      op.color = 'red';
      op.display = '删除';
      break;
    case 'getbyid':
      op.color = 'purple';
      op.display = '按Id读取';
      break;
    case 'getbyname':
      op.color = 'gold';
      op.display = '按名读取';
      break;
    default:
      // 随机分配一个颜色
      const colors = [
        'orange',
        'purple',
        'gold',
        'magenta',
        'lime',
        'volcano',
        'geekblue',
        'gray',
        'cyan',
      ];
      const randomIndex = Math.floor(Math.random() * colors.length);
      op.color = colors[randomIndex];
      break;
  }

  return op;
}

// 提交表单
async function handleSubmit() {
  // 验证表单
  const hasEmptyFields = operations.value.some((op) => !op.code || !op.display);

  if (hasEmptyFields) {
    message.error('操作代码和显示名称不能为空');
    return;
  }

  try {
    submitting.value = true;

    // 准备更新的资源数据
    const updatedResource: ResourceInDto = {
      ...props.resource,
      allowedOperations: operations.value,
    };

    // 调用API更新资源
    await updateResourcesApi([updatedResource], props.service);

    message.success('操作权限更新成功');
    emit('success');
    emit('update:open', false);
  } catch (error) {
    console.error('更新操作权限失败:', error);
    message.error('更新操作权限失败');
  } finally {
    submitting.value = false;
  }
}
</script>

<style scoped>
.operations-form {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 10px;
}

.operation-header {
  display: flex;
  gap: 8px;
  align-items: center;
  padding: 0 8px 8px;
  border-bottom: 1px solid #f0f0f0;
  font-weight: bold;
  color: #666;
}

.header-code,
.operation-code {
  width: 200px;
}

.header-display,
.operation-input {
  width: 150px;
}

.header-color,
.operation-color-select {
  width: 120px;
}

.header-access-type,
.operation-access-type-select {
  width: 120px;
}

.header-preview,
.preview-tag {
  width: 150px;
  text-align: center;
}

.operation-item {
  margin-bottom: 8px;
  padding: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.operation-row {
  display: flex;
  gap: 8px;
  align-items: center;
}

.operation-code {
  color: #666;
}

.operation-input {
  flex: none;
}

.preview-tag {
  margin: 0;
}

.color-dot {
  display: inline-block;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  margin-right: 8px;
  vertical-align: middle;
}

.color-dot.blue {
  background-color: #1890ff;
}
.color-dot.red {
  background-color: #f5222d;
}
.color-dot.green {
  background-color: #07a568;
}
.color-dot.orange {
  background-color: #fa8c16;
}
.color-dot.purple {
  background-color: #722ed1;
}
.color-dot.gold {
  background-color: #a16f0a;
}
.color-dot.magenta {
  background-color: #f78cc7;
}
.color-dot.lime {
  background-color: #29f834;
}
.color-dot.volcano {
  background-color: #fa541c;
}
.color-dot.geekblue {
  background-color: #08228b;
}
.color-dot.gray {
  background-color: #8c8c8c;
}
.color-dot.cyan {
  background-color: #13c2c2;
}
</style>
